import {
  getPage
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  $empty,
  $toast,
  storage,
  Validate
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    regionInfo: [],
    pickerArea: true,
    areaShow: false,
    pickerValue: '110101',
    tongbu: true,
    id: 0,
    areaList: {
      province_list: {},
      city_list: {},
      county_list: {},
    },
    content: '',
    fileList: [],
    fileList_xq: [],
    videoList: [],
    addressForm: {
      title: '',
      description: '',
      contacter: '',
      tel: '',
      address: '',
      location: '',
      locationId: [],
      Category: ''
    }
  },
  onfabuChange({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      tongbu: detail
    });
  },
  afterReadxq(event) {
    const {
      file
    } = event.detail;
    var that = this;
    var fileList_xq = that.data.fileList_xq;

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "products",
        success(res) {

          fileList_xq.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            fileList_xq: fileList_xq
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },
  videoafterRead(event) {
    const {
      file
    } = event.detail;
    var that = this;
    console.log(file)
    var videoList = that.data.videoList;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "anli",
        success(res) {
          // 上传完成需要更新 fileList
          console.log(res);
          videoList.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            videoList: videoList
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }

    console.log(videoList);
  },
  toggle(type) {
    this.setData({
      [type]: !this.data[type]
    });
  },
  /**
   * 城市选择open || close
   */
  pickerAreaTap() {
    this.toggle('areaShow');
  },
  pickerCategoryTap() {
    this.toggle('categoryShow');
  },
  /**
   * 确定选择城市
   */
  pickerAreaConfirm(e) {
    const {
      index,
      values
    } = e.detail;
    const {
      regionInfo
    } = this.data;
    const provice = regionInfo[index[0]];
    const city = provice.list[index[1]];
    const county = city.list[index[2]];
    this.setData({
      locationError: '',
      'addressForm.location': `${provice.name} ${city.name} ${county.name}`,
      'addressForm.locationId': [provice.id, city.id, county.id],
    });
    this.pickerAreaTap();
  },
  /**
   * 获取地区
   */
  getRegionInfo() {
    return new Promise((resolve) => {
      storage.get('regionInfo').then((res) => {
        this.setData({
          regionInfo: res,
          pickerArea: false
        });
        resolve(res);
      }).catch((res) => {
        http.get(api.default, {
          data: {
            action: 'district'
          }
        }, false).then((res) => {
          const {
            data
          } = res.data;
          this.setData({
            regionInfo: data,
            pickerArea: false
          });
          storage.set('regionInfo', data);
          resolve(data);
        });
      });
    });
  },
  /**
   * 城市数据格式转换
   * @整体是一个 Object，包含 province_list, city_list, county_list 三个 key。
   * @每项以省市区编码作为 key，省市区名字作为 value。编码为 6 位数字，前两位代表省份，中间两位代表城市，后两位代表区县，以 0 补足 6 位。如北京编码为 11，以零补足 6 位，为 110000。
   */
  formatArea() {
    const {
      regionInfo,
      areaList
    } = this.data;
    let {
      province_list,
      city_list,
      county_list
    } = areaList;

    //一级 省份
    regionInfo.forEach((parentsItem, parentsIndex) => {
      parentsIndex = (parentsIndex + 11).toString();
      let parentsCode = parentsIndex;
      let parentsLength = parentsIndex.length;
      if (parentsLength < 6) {
        for (let i = 0; i < 6 - parentsLength; i++) {
          parentsCode = parentsCode + `0`;
        }
      }

      //二级 城市
      if (parentsItem.list.length) {
        parentsItem.list.forEach((parentItem, parentIndex) => {
          //从1开始
          parentIndex = (parentIndex + 1).toString();
          if (parentIndex < 10) {
            parentIndex = `0` + parentIndex;
          }
          parentIndex = parentsIndex + parentIndex;
          let parentCode = parentIndex;
          let parentLength = parentIndex.length;
          if (parentLength < 6) {
            for (let i = 0; i < 6 - parentLength; i++) {
              parentCode = parentCode + `0`;
            }
          }
          city_list[parentCode] = parentItem.name;

          //三级 区
          if (parentItem.list.length) {
            parentItem.list.forEach((item, index) => {
              //从1开始
              index = (index + 1).toString();
              if (index < 10) {
                index = `0` + index;
              }
              index = parentIndex + index;
              let code = index;
              let length = index.length;
              if (length < 6) {
                for (let i = 0; i < 6 - length; i++) {
                  code = code + `0`;
                }
              }
              county_list[code] = item.name
            });
          }
        });
      }
      province_list[parentsCode] = parentsItem.name;
    });

    this.setData({
      areaList
    });
  },
  titleInput(e) {
    this.setData({
      titleInputError: '',
      'addressForm.title': e.detail,
    });
  },
  descriptionInput(e) {
    this.setData({
      descriptionInputError: '',
      'addressForm.description': e.detail,
    });
  },
  ordersInput(e) {
    this.setData({
      ordersError: '',
      "addressForm.orders": $empty(e.detail)
    })
  },
  contacterInput(e) {
    this.setData({
      'addressForm.contacter': e.detail,
    });
  },
  telInput(e) {
    this.setData({
      'addressForm.tel': e.detail,
    });
  },
  addressInput(e) {
    this.setData({
      'addressForm.address': e.detail,
    });
  },
  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      'addressForm.Category': value
    })
    this.toggle('categoryShow');
  },
  /**
   * 所在地址
   */
  locationInput(e) {
    this.setData({
      locationError: '',
      'addressForm.location': e.detail
    })
  },
  deleteimg(event) {
    var index = event.detail.index;
    var fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList: fileList
    });
  },
  deleteimgxq(event) {
    var index = event.detail.index;
    var fileList_xq = this.data.fileList_xq;
    fileList_xq.splice(index, 1);
    this.setData({
      fileList_xq: fileList_xq
    });
  },
  deletevideo(event) {
    var index = event.detail.index;
    var videoList = this.data.videoList;
    videoList.splice(index, 1);
    this.setData({
      videoList: videoList
    });
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    var that = this;
    var fileList = that.data.fileList; 

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "anli",
        success(res) {
          // 上传完成需要更新 fileList

          fileList.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            fileList: fileList
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },
  /**
   * 提交保存
   */
  anliForm(e) {
    Validate.check(this, this.expressValidate, e.detail.value, (res) => {
      if (res) {
        const data = this.data;
        const fileList = data.fileList;
        const fileList_xq = data.fileList_xq;
        if (fileList.length == 0) {
          $toast("请上传图片");
          return;
        }
        const {
          shopid,
          userId,
          tongbu,
          videoList,
          id
        } = this.data;
        const {
          title,
          description,
          contacter,
          tel,
          address,
          location,
          locationId,
          Category,
          orders
        } = data.addressForm;
        const params = {
          action: 'adddesign',
          id: id,
          title: title,
          orders: orders||0,
          tongbu: tongbu,
          description: description,
          contacter: contacter,
          tel: tel,
          address: address,
          province_id: locationId[0],
          city_id: locationId[1],
          district_id: locationId[2],
          userid: userId,
          shopid: shopid,
          Category: Category,
          fileList: JSON.stringify(fileList),
          xqlist: JSON.stringify(fileList_xq),
          videoList: JSON.stringify(videoList)
        }
        http.post(api.default, {
          data: params
        }).then((res) => {
          if (res.data.code == 0) {
            $toast('保存成功', {
              icon: 'success'
            });
            const pages = getCurrentPages()[getCurrentPages().length - 2];

            wx.navigateBack({
              delta: 1,
              success() {
                if (pages !== undefined || pages !== null) {
                  pages.data.pageChange = 1;
                  pages.onLoad();
                }
              }
            });
          } else {
            $toast(res.data.errmsg, {
              icon: 'fail'
            });
          }
        });
      } else {
        $toast("请输入标题和内容");
      }
    });

  },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    app.getLogin().then((res) => {
      this.setData({
        userInfo: res,
        logged: res.code,
        userId: res.data.user.user_id,
        shopid: res.data.shop.ShopId
      });
      // //店铺案例
      // http.post(api.default, {
      //   data: {
      //     action: 'GetShopanli',
      //     shopid: res.data.shop.ShopId
      //   }
      // }, false).then((res) => {
      //   const {
      //     data
      //   } = res.data;
      //   this.setData({
      //     fileList: data.list,
      //     content: data.des
      //   });
      // });
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    });
    /**
     * 获取地区
     */
    this.getRegionInfo().then((res) => {
      //地区格式化
      this.formatArea();
      //如果修改地址

      const data = this.data;
      if (data.zonedata != null) {
        const {
          district
        } = data.zonedata;
        const {
          county_list
        } = data.areaList;
        Object.entries(county_list).map((key) => {
          if (district.name == key[1]) {
            this.setData({
              pickerValue: key[0],
            })
          }
        })
      }
    });
    http.post(api.default, {
      data: {
        action: 'getselectcategory'
      }
    }, false).then((res) => {
      const {
        data
      } = res.data;
      console.log(res.data);
      this.setData({
        columns: data
      });
    });
    if (JSON.stringify(options) !== '{}') {
      this.setData({
        id: options.id
      });
      http.post(api.default, {
        data: {
          action: 'getdesigninfo',
          id: options.id
        }
      }).then((res) => {
        const data = res.data.data;
        this.setData({
          'addressForm.title': data.info.title,
          'addressForm.orders': data.info.orders,
          'addressForm.description': data.info.description,
          fileList: data.filelist,
          fileList_xq: data.xqlist,
          videoList: data.videolist
        });
      });
    }
    //获取验证规则
    Validate.rules('#title,#description', (res) => {
      this.expressValidate = res;
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})